package com.xxgc.cloud.consumer.springcloudconsumer.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.xxgc.cloud.api.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @program: SpringCloudStudy
 * @description: 流量控制测试
 * @author: Shijiayi
 * @create: 2022-12-06 16:22
 **/
@Api(tags = "流控测试")
@RestController
@RequestMapping("/sentinel")
public class SentinelController {

    private static int a = 1;

    //懒加载机制 必须被调用过才能找到
    //定义资源 value是资源名字
    @SentinelResource(value = "addOrder",blockHandler="orderExcessiveFlow",fallback="orderFallback")
    @ApiOperation(value = "模拟下单操作")
    @PostMapping("/addOrder")
    public Result addOrder(@RequestParam Integer orderId){
        a++;
        if(a % 3 == 0){
            throw new RuntimeException("熔断");
        }
        return Result.success("下单成功"+orderId+"---"+new Date());
    }
    //订单请求量过大
    public static Result orderExcessiveFlow(Integer orderId, BlockException e){
        return Result.error("服务器压力过大请稍后重试！");
    }
    //异常熔断
    public Result orderFallback(Integer orderId){
        return Result.error("糟糕，我被熔断了！");
    }


    @ApiOperation(value = "用于触发熔断效果")
    @PostMapping("/chageA")
    public Result changeA(){
        a = 1;
        return Result.success("修改成功");
    }

}
